package com.gateway.springboot.starter.gateway.filter;

import com.gateway.common.config.GatewayConfig;
import com.gateway.common.dto.PluginData;
import com.gateway.common.enums.PluginHandlerEventEnum;
import com.gateway.plugin.api.GatewayPlugin;
import com.gateway.plugin.api.GatewayPluginChain;
import com.gateway.plugin.base.cache.BaseDataCache;
import com.gateway.plugin.base.cache.PluginHandlerEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @program: api-gateway
 * @description:
 * @author: YuKai Fan
 * @create: 2025/2/6 10:20
 **/
public class GatewayPluginGlobalFilter implements GlobalFilter, Ordered, ApplicationListener<PluginHandlerEvent> {
    private static final Logger log = LoggerFactory.getLogger(GatewayPluginGlobalFilter.class);

    /**
     * this filed can not set to be final, because we should copyOnWrite to update plugins.
     */
    private volatile List<GatewayPlugin> plugins;

    /**
     * source plugins, these plugins load from GatewayPlugin, this filed can't change.
     */
    private final List<GatewayPlugin> sourcePlugins;

    private final boolean scheduled;

    private Scheduler scheduler;

    public GatewayPluginGlobalFilter(List<GatewayPlugin> plugins, final GatewayConfig gatewayConfig) {
        this.sourcePlugins = new ArrayList<>(plugins);
        this.plugins = new ArrayList<>(plugins);
        GatewayConfig.Scheduler config = gatewayConfig.getScheduler();
        this.scheduled = config.getEnabled();
        if (scheduled) {
            if (Objects.equals(config.getType(), "fixed")) {
                this.scheduler = Schedulers.newParallel("gateway-work-threads", config.getThreads());
            } else {
                this.scheduler = Schedulers.boundedElastic();
            }
        }
        this.plugins = plugins;
    }


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return new DefaultGatewayPluginChain(chain, plugins).execute(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    /**
     * listen plugin handler event and handle plugin.
     *
     * @param event sort plugin event
     */
    @Override
    public void onApplicationEvent(final PluginHandlerEvent event) {
        PluginHandlerEventEnum stateEnums = event.getPluginStateEnums();
        PluginData pluginData = (PluginData) event.getSource();
        switch (stateEnums) {
            case ENABLED:
                onPluginEnabled(pluginData);
                break;
            case DELETE:
            case DISABLED:
                // disable or removed plugin.
                onPluginRemoved(pluginData);
                break;
            case SORTED:
                // copy a new one, or there will be concurrency problems
                this.plugins = sortPlugins(new ArrayList<>(this.plugins));
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + event.getPluginStateEnums());
        }
    }

    /**
     * sort plugins.
     *
     * @param list list of plugin
     * @return sorted list
     */
    private List<GatewayPlugin> sortPlugins(final List<GatewayPlugin> list) {
        Map<String, Integer> pluginSortMap = list.stream().collect(Collectors.toMap(GatewayPlugin::named, plugin -> {
            PluginData pluginData = BaseDataCache.getInstance().obtainPluginData(plugin.named());
            return Optional.ofNullable(pluginData).map(PluginData::getSort).orElse(plugin.getOrder());
        }));
        list.sort(Comparator.comparingLong(plugin -> pluginSortMap.get(plugin.named())));
        return list;
    }

    /**
     * handle enabled plugins.
     * @param pluginData plugin data
     */
    private synchronized void onPluginEnabled(final PluginData pluginData) {
        log.info("gateway use plugin:[{}]", pluginData.getName());
        final List<GatewayPlugin> enabledPlugins = this.sourcePlugins.stream().filter(plugin -> plugin.named().equals(pluginData.getName())
                && pluginData.getEnabled()).collect(Collectors.toList());
        enabledPlugins.removeAll(this.plugins);
        // copy a new plugin list.
        List<GatewayPlugin> newPluginList = new ArrayList<>(this.plugins);
        newPluginList.addAll(enabledPlugins);
        this.plugins = sortPlugins(newPluginList);
    }

    /**
     * handle removed or disabled plugin.
     * @param pluginData plugin data
     */
    private synchronized void onPluginRemoved(final PluginData pluginData) {
        // copy a new plugin list.
        List<GatewayPlugin> newPluginList = new ArrayList<>(this.plugins);
        newPluginList.removeIf(plugin -> plugin.named().equals(pluginData.getName()));
        this.plugins = newPluginList;
    }

    private static class DefaultGatewayPluginChain implements GatewayPluginChain {

        private int index;

        private final GatewayFilterChain chain;

        private final List<GatewayPlugin> plugins;

        /**
         * Instantiates a new Default gateway plugin chain.
         *
         * @param chain
         * @param plugins the plugins
         */
        DefaultGatewayPluginChain(GatewayFilterChain chain, final List<GatewayPlugin> plugins) {
            this.chain = chain;
            this.plugins = plugins;
        }

        /**
         * Delegate to the next {@code WebFilter} in the chain.
         *
         * @param exchange the current server exchange
         * @return {@code Mono<Void>} to indicate when request handling is complete
         */
        @Override
        public Mono<Void> execute(final ServerWebExchange exchange) {
            if (this.index < plugins.size()) {
                GatewayPlugin plugin = plugins.get(this.index++);
                boolean skip = plugin.skip(exchange);
                if (skip) {
                    return this.execute(exchange);
                }
                return plugin.execute(exchange, this);
            }
            return chain.filter(exchange);
        }
    }
}
